job "echo" {
  datacenters = ["dc1"]
  type        = "service"

  # 基于资源指标的自动扩缩容策略
  scaling {
    enabled = true
    min     = 1
    max     = 5

    # CPU 扩容策略（当平均使用率 > 70% 时扩容）
    policy {
      source = "prometheus"
      query  = <<EOF
        avg(
          nomad_client_allocs_cpu_total_percent{task="echo"}
        ) by (job)
      EOF
      strategy {
        name   = "target-value"
        config = { target = 70 } # 目标CPU使用率70%
      }
    }

    # 内存扩容策略（当平均使用率 > 80% 时扩容）
    policy {
      source = "prometheus"
      query  = <<EOF
        avg(
          nomad_client_allocs_memory_usage_bytes{task="echo"} /
          nomad_client_allocs_memory_limit_bytes{task="echo"} * 100
        ) by (job)
      EOF
      strategy {
        name   = "target-value"
        config = { target = 80 } # 目标内存使用率80%
      }
    }
  }

  group "echo" {
    count = 1

    network {
      port "http" { to = 9999 }  # 固定容器端口
      port "metrics" { to = 9100 } # Prometheus 指标端口
    }

    service {
      name = "api-service"
      port = "http"
      tags = ["metrics_port=9100", "metrics_path=/metrics"]

      check {
        type     = "http"
        path     = "/health"
        interval = "10s"
      }
    }

    task "api-server" {
      driver = "docker"
      config {
        image = "registry.cn-hangzhou.aliyuncs.com/my_public_images/echo:latest"
        ports = ["http", "metrics"]
      }

      # 关键：设置资源限制（触发扩缩容的基准）
      resources {
        cpu    = 100  # 500 MHz
        memory = 64  # 512 MB
      }

      # 暴露 Nomad 内置指标给 Prometheus
      template {
        data = <<EOF
        NOMAD_CPU_LIMIT={{ env "NOMAD_CPU_LIMIT" }}
        NOMAD_MEMORY_LIMIT={{ env "NOMAD_MEMORY_LIMIT" }}
        EOF
        destination = "local/env.txt"
        env         = true
      }
    }
  }
}